

workspace_functions = {
    view_save : function(elements){
	$("body").on("click",elements,function(){
	    var form_type = $(this).attr("data-form-type");
	    var modal_title = $(this).attr("data-workspace");
		//jDialog(message, value,width, height, top, function(){});
		var save_string = save_workspace(form_type,modal_title);
		
		jDialog(save_string, "","", "", "", function(){
		    
		});
		disableFormSettings()
	});
    },
    preview_form : function(elements){
	$("body").on("click",elements,function(){
	    var form_type = $(this).attr("data-form-type");
	    var workspace_width = $(".form_size_width").val();
	    var workspace_height = $(".form_size_height").val();
	    // Get Button
		var btnName = $(".setObject_btn").map(function(){
		    return $(this).children().val();
		}).get().join();
		
		switch (form_type) {
		    case "organizational_chart":
			var workspace_content = $(".orgchart_ws").html();
			
			    var workspace = {};
				workspace["WorkspaceHeight"] = workspace_height;
				workspace["WorkspaceWidth"] = workspace_width;
				workspace['WorkspaceContent'] = workspace_content;
				workspace['BtnName'] = btnName;
				var json_encode = JSON.stringify(workspace);
				pid = json_encode;
				workspace_width = parseInt(workspace_width)+15;
			    //$.post('/preview', {json_encode:json_encode }, function() {
				var win = window.open('/workspace?view_type=preview&formWidth='+workspace_width+'&formHeight='+workspace_height+'&type=orgchart','_blank');
				win.focus();
			break;
		    
		    case "formbuilder":
			var workspace_content = $(".formbuilder_ws").html();
			   
			   var workspace = {};
				workspace["WorkspaceHeight"] = workspace_height;
				workspace["WorkspaceWidth"] = workspace_width;
				workspace['WorkspaceContent'] = workspace_content;
				workspace['BtnName'] = btnName;
				var json_encode = JSON.stringify(workspace);
				pid = json_encode;
			    //$.post('/preview', {json_encode:json_encode }, function() {
				var win = window.open('/workspace?view_type=preview&formWidth='+workspace_width+'&formHeight='+workspace_height,'_blank');
				win.focus();
				
			    //});
			break;
		    
		    case "workflow":
			var workspace_content = $(".workflow_ws").html();
			
			    var workspace = {};
				workspace["WorkspaceHeight"] = workspace_height;
				workspace["WorkspaceWidth"] = workspace_width;
				workspace['WorkspaceContent'] = workspace_content;
				workspace['BtnName'] = btnName;
				var json_encode = JSON.stringify(workspace);
				pid = json_encode;
				workspace_width = parseInt(workspace_width)+15;
			    //$.post('/preview', {json_encode:json_encode }, function() {
				var win = window.open('/workspace?view_type=preview&formWidth='+workspace_width+'&formHeight='+workspace_height+'&type=flowchart','_blank');
				win.focus();
			break;
		    case "generate":
			var workspace_content = $(".formbuilder_ws").html();
			var formID = $("#FormId").val();
			var requestID = $("#requestID").val();
			var trackNo = $("#trackNo").val();
			    var workspace = {};
				workspace["WorkspaceHeight"] = workspace_height;
				workspace["WorkspaceWidth"] = workspace_width;
				workspace['WorkspaceContent'] = workspace_content;
				workspace['WorkspaceFormID'] = formID
				workspace['WorkspaceRequestID'] = requestID
				workspace['WorkspaceTrackNo'] = trackNo
				workspace['BtnName'] = btnName;
				var json_encode = JSON.stringify(workspace);
				pid = json_encode;
				    var win = window.open('/workspace?view_type=preview&formWidth='+workspace_width+'&formHeight='+workspace_height+'&formID='+formID,'_blank');
				
			    //$.post('/preview', {json_encode:json_encode }, function() {
				win.focus();
			break;
		}
	});
    },
    save_form_workspace : function(elements){
	$("body").on("click",elements,function(){
	    
	    var form_type = $(this).attr("data-form-type");
	// Settings
	    var workspace_title = $(".workspace_title").val();
	    var workspace_displayName = $(".workspace_displayName").val();
	    var workspace_prefix = $(".workspace_prefix").val();
	    var workspace_type = $(".workspace_type option:selected").val();
	    var workspace_width = $(".form_size_width").val();
	    var workspace_height = $(".form_size_height").val();
	
	
	    
	});
    }
}

// Open / Close Settings on Workspace
$(function ($) {
    $.fn.extend({
	formbuilder: function (options) {
            
            var settings = {
                type : "open", // Default action for panel settings
		auto_open : "true" // Auto Open
                
            };
            
            options = $.extend(settings, options);
            
            return this.each(function() {
                var o =options;
                var obj = $(this);
             
            // Open Close Properties   
                if (o.type=="open") {

                    $("body").on("click",".form_settings_open",function(){
                        // Functions for open panel settings
                         var pos = {
							pos_top_action : "-212",
							pos_top_prop_action : "0"
						    }
                       
                        form_settings(this,".form_properties",".form_properties_actions","form_settings_open","form_settings_close",pos);
                        
                    });     
                }else{
					$("body").on("click",".form_settings_close",function(){

					    // Functions for close panel settings
					    var pos = {
                            pos_top_action : "0",
                            pos_top_prop_action : "211"
                        }
					    form_settings(this,".form_properties",".form_properties_actions","form_settings_close","form_settings_open",pos);
					    
					});	
		    //}
                    
                }
                
            });
	}
    });
    
    
});
/*---------------------------------------- Functions for Form Builder ---------------------------------*/

/*
 * Functions for open / close panel
 *
 */

function form_settings(elements,panel,panel_settings,panel_actions_remove,panel_action,pos) {
    
    $(panel).animate({right:pos.pos_top_action},"slow");
    $(panel_settings).animate({right:pos.pos_top_prop_action},"slow");
    $(elements).removeClass(panel_actions_remove);
    $(elements).addClass(panel_action);
    
}

/*
 * Ruler
 *
 */

    function dragShowHorizontalRuler(passedElement, mouseX, mouseY,container){
	    container_of_passed_ele = $(passedElement).closest(container);
	    if($(".ws-ruler-horizontal-row-guide").length >= 1 ){
		    
		    $(".ws-ruler-horizontal-row-guide").css({
			    top:/*passedElement.offset().top+1*/mouseY - container_of_passed_ele.offset().top
		    });
	    }else{
    
		    tempAppendShowRulerHorizontalRowGuide = $('<span class="draggable ui-draggable ws-ruler-horizontal-row-guide"></span>');
    
		    container_of_passed_ele.append(tempAppendShowRulerHorizontalRowGuide);
    
		    tempAppendShowRulerHorizontalRowGuide.css({
			    top:/*passedElement.offset().top+1*/mouseY - container_of_passed_ele.offset().top,
			    left:0
		    });
	    }
	    ruler_h_top = $(".ws-ruler-horizontal-row-guide").offset().top - container_of_passed_ele.offset().top;
	    if(ruler_h_top != (passedElement.offset().top - container_of_passed_ele.offset().top) ){
		    $(".ws-ruler-horizontal-row-guide").css({
			    top:/*passedElement.offset().top*/mouseY - container_of_passed_ele.offset().top
		    });
	    }
    }
    function dragShowVerticalRuler(passedElement, mouseX, mouseY,container){
	    container_of_passed_ele = $(passedElement).closest(container);
	    if($(".ws-ruler-vertical-column-guide").length >= 1 ){
		    
		    $(".ws-ruler-vertical-column-guide").css({
			    left:/*passedElement.offset().left*/mouseX - container_of_passed_ele.offset().left
		    });
	    }else{

		    tempAppendShowRulerVerticalColumnGuide = $('<span class="draggable ui-draggable ws-ruler-vertical-column-guide"></span>');
    
		    container_of_passed_ele.append(tempAppendShowRulerVerticalColumnGuide);
    
		    tempAppendShowRulerVerticalColumnGuide.css({
			    left:mouseX - container_of_passed_ele.offset().left,
			    top:0
		    });
	    }
	    ruler_v_left = $(".ws-ruler-vertical-column-guide").offset().left - container_of_passed_ele.offset().left;
	    if(ruler_v_left != (passedElement.offset().left - container_of_passed_ele.offset().left) ){
		    $(".ws-ruler-vertical-column-guide").css({
			    left:/*passedElement.offset().left*/mouseX - container_of_passed_ele.offset().left
		    });
	    }
    }
    function removeRuler(){
	$(".ws-ruler-horizontal-row-guide").remove();
	$(".ws-ruler-vertical-column-guide").remove();
    }

    

/*
 * Call Save Functions Design
 *      Via Ctrl + S
 *
 */

function control_save_workspace(elements) {
    //handles ctrl-s
	$(document).keydown(function(event) {
	    var pathname = window.location.pathname;
	    if (pathname.indexOf("organizational_chart") >= 0 || pathname.indexOf("formbuilder") >= 0  || pathname.indexOf("workflow") >= 0 || pathname.indexOf("report") >= 0 || pathname.indexOf("generate") >= 0){
		    var currKey=0,e=e||event; 
		    currKey=e.keyCode||e.which||e.charCode;  //do this handle FF and IE
			if (!( String.fromCharCode(event.which).toLowerCase() == 's' && event.ctrlKey) && !(event.which == 19)) return true;
			    event.preventDefault();
			    
			    var form_type = $(elements).attr("data-form-type");
			    var modal_title = $(elements).attr("data-workspace");
			    if(!modal_title){
			    	return;
			    }
			    
			    /* Save Functions Design */
				var save_string = save_workspace(form_type,modal_title);
				//jDialog(message, value,width, height, top, function(){});
				jDialog(save_string, "","", "", "", function(){});
						
						disableFormSettings()
		    return false;
	    }
	    
	});
}


/*
 * Save Functions Design
 *      Containing (Organizational Chart, Formbuilder, Workflow);
 *      @form_type = validation of save functions details
 *      @modal_title = set the title of save properties modal
 *
 */

function save_workspace(form_type,modal_title) {
    var json = $("body").data();
    var ret = '';
    var pathname = window.location.pathname;
        if (pathname=="/generate"){
	    var disabled = "disabled=disabled";
	}else{
	    var disabled = "";
	}
    ret += '<h3>';
	    ret += '<i class="icon-save"></i> ' + modal_title;
	ret += '</h3>';
	ret += '<div class="hr"></div>';
	ret += '<div class="fields">';
	    ret += '<div class="label"> Details: </div>';
	//    if (form_type=="formbuilder") {
	//    ret += '<div class="input_position" style="text-align:center;">';
	//	ret += '<img data-original-title="" src="http://eforms.gs3.com.ph:80/images/avatar/small.png" width="44" height="44" class="avatar userAvatar">';
	//    ret += '</div>';
	//    }
	ret += '</div>';
	
	ret += '<div class="fields">';
	    ret += '<div class="label_basic"> Title:<font color="red">*</font> </div>';
	    ret += '<div class="input_position">';
		ret += '<input type="text" name="workspace_title" ' + disabled + ' id="workspace_title" class="workspace_title form-text" style="margin-top:5px;" value="'+ if_undefinded(json.workspace_title,"") +'">';
	    ret += '</div>';
	ret += '</div>';
    
    // For Organizatioanl Chart And Workflow Description
    if (form_type!="formbuilder") {
	ret += '<div class="fields">';
	    ret += '<div class="label_basic"> Description: </div>';
	    ret += '<div class="input_position">';
		ret += '<textarea class="form-textarea_save workspace_description" name="workspace_description" id="workspace_description" style="resize:none"></textarea>';
	    ret += '</div>';
	ret += '</div>';
    }
	    
	if (form_type=="formbuilder" || form_type=="generate") {
	    
	    /*
	     * Workspace formbuilder
	     */
	     
		ret += '<div class="fields">';
		    ret += '<div class="label_basic"> Display Name:<font color="red">*</font> </div>';
		    ret += '<div class="input_position">';
			ret += '<input type="text" name="workspace_displayName" id="workspace_displayName" class="workspace_displayName form-text" style="margin-top:5px;" value="'+ if_undefinded(json.workspace_displayName,"") +'">';
		    ret += '</div>';
		ret += '</div>';
		
		if(form_type!="generate"){    
		    ret += '<div class="fields">';
			ret += '<div class="label_basic"> Form Category: </div>';
			ret += '<div class="input_position">';
			    ret += '<select class="form-select form_category" name="form_category" id="form_category" style="margin-top:5px;">';
				ret += getFormCategory();
			    ret += '</select>';
			ret += '</div>';
		    ret += '</div>';
		    ret += '<div class="fields">';
			ret += '<div class="label_basic"> Form Logo: </div>';
			ret += '<div class="input_position">';
			    ret += '<form action="/ajax/uploadFile" method="POST" class="formLogo" id="formLogo" enctype="multipart/form-data">';
			    ret += '<div id="uniform-fileInput" class="uploader" style="margin-top:5px;">';
				ret += '<input type="file" data-action-id="2" value="upload" name="uploadLogoForm" id="uploadLogoForm" size="24" data-action-type="uploadLogoForm" style="opacity: 0;" class="upfile">';
				ret += '<span id="uploadFilename_2" class="filename">No file selected</span>';
				ret += '<span class="action">Choose File</span>';
				ret += '<input type="hidden" value="postLogoUpload" name="uploadType">';
			    ret += '</div>';
			    ret += '</form>';
			    ret += '<img src="/images/loader/load.gif" class="postLogoLoader display" style="margin-top: 13px;margin-left: 5px;">';
			ret += '</div>';
		    ret += '</div>';
		    ret += '<div class="fields">';
			ret += '<div class="label"> Reference Format:</div>';
		    ret += '</div>';
		    ret += '<div class="fields">';
			ret += '<div class="label_basic"> Prefix:<font color="red">*</font>  </div>';
			ret += '<div class="input_position">';
			    ret += '<input type="text" name="workspace_prefix" value="'+ if_undefinded(json.workspace_prefix,"") +'" id="workspace_prefix" class="workspace_prefix form-text" style="margin-top:5px;">';
			ret += '</div>';
		    ret += '</div>';
		    ret += '<div class="fields">';
			ret += '<div class="label_basic"> Type:<font color="red">*</font> </div>';
			ret += '<div class="input_position">';
			    ret += '<select class="form-select workspace_type" name="workspace_type" id="workspace_type" style="margin-top:5px;">';
				ret += '<option value="0">----------------------------Select----------------------------</option>';
				ret += '<option '+ setSelected("Sequential", if_undefinded(json.workspace_type,"")) +'>Sequential</option>';
				ret += '<option '+ setSelected("DateTime", if_undefinded(json.workspace_type,"")) +'>DateTime</option>';
			    ret += '</select>';
			ret += '</div>';
		    ret += '</div>';
		}

			//ret += '<input type="text" name="" id="" class=" form-text" style="margin-top:5px;">';
		    ret += '</div>';
		ret += '</div>';
	}else{
		if (form_type=="organizational_chart") {
		    /*
		    * Workspace Organizational Chart
		    */	
			ret += '<div class="fields">';
			    ret += '<div class="label_basic"> Status: <font color="red">*</font></div>';
			    ret += '<div class="input_position">';
				ret += '<select class="form-text workspace_status" name="workspace_status" id="workspace_status" style="margin-top:5px;">';
				    ret += '<option value="null">----------------------------Select----------------------------</option>';
				    ret += '<option value="1">Activate</option>';
				    ret += '<option value="0">Deactivate</option>';
				ret += '</select>';
			    ret += '</div>';
			ret += '</div>';
		}
	}
    
    /*
     * Modal Action Button
     * Save / Cancel
     *
     */
	
	ret += '<div class="fields">';
	    ret += '<div class="label_basic"></div>';
	    ret += '<div class="input_position" style="margin-top:5px;text-align:right;">';
		ret += '<img src="/images/loader/load.gif" class="display saveFormLoad" style="margin-right:5px;margin-top:2px;"/>';
		ret += '<input type="button" class="btn-blueBtn save_form_workspace" data-form-type="' + form_type + '" id="save_form_workspace" value="Save">     ';
		ret += '<input type="button" class="btn-basicBtn" id="popup_cancel" value="Cancel">';
	    ret += '</div>';
	ret += '</div>';
	
    return ret;
}
function disableFormSettings(){
	// var pathname = window.location;
	// if(getParametersName("view_type",pathname)=="edit"){
	// 	$("#workspace_title").attr("disabled","disabled");
	// 	$("#workspace_displayName").attr("disabled","disabled");
	// 	$("#workspace_prefix").attr("disabled","disabled");
	// 	$("#workspace_type").attr("disabled","disabled");
	// }
}

function getFormCategory() {
	var json = $("body").data();
	// console.log(json)
    var ret = ""
    ret += '<option value="0">----------------------------Select----------------------------</option>';
    $.ajax({
	type : "POST",
	url  : "/ajax/formbuilder",
	data : {action:"getCategory"},
	dataType : "json",
	success : function(data){
	    $.each(data, function(id,val){
		ret += '<option value="' + data[id].category_id + '" ' + setSelected(json['form_category'],data[id].category_id) + '>' + data[id].category_name + '</option>';
	
	    });
	    $(".form_category").append(ret);
	}
    });
}

RequestPivacy = {
	"authors" : function(){
		//alert("authors")
		jDialog(this.setDialog("Form Authors","form-authors",""), "","600", "", "", function(){});
		this.otherAttributes();
	},
	"readers" : function(){
		//alert("readers")
		var note = "Note: Requestor and Current Approver can automatically view the request.";
		jDialog(this.setDialog("Request Viewer","form-readers",note), "","600", "", "", function(){});
		this.otherAttributes();
	},
	"admin" : function(){
		jDialog(this.setDialog("Form Admin","form-admin",""), "","600", "", "", function(){});
		this.otherAttributes();
	},
	"customizedPrint" : function(){
		jDialog(this.setDialog("Customized Print Author","customized-print",""), "","600", "", "", function(){});
		this.otherAttributes();
	},
	"otherAttributes" : function(){
		this.setCheckAllChecked(".fp-user");
		this.bindOnClickCheckBox();
		limitText(".limit-text-ws",20);
		$(".tip").tooltip();
		$('#content-dialog-scroll').perfectScrollbar();
	},
	"setDialog" : function (title,type,note){
		var self = this;
		var json = $("body").data();
		var formPrivacy = if_undefinded(json[''+ type +''],"");
		var departments_arr;var positions_arr;var users_arr;
		if(formPrivacy){
			departments_arr = formPrivacy['departments'];
			positions_arr = formPrivacy['positions'];
			users_arr = formPrivacy['users'];
		}
		var departments = $(".departments").text();
		var positions = $(".positions").text();
		var users = $(".users").text();
		var ret = '<h3>';
		    ret += '<i class="icon-save"></i> ' + title;
			ret += '</h3>';
			ret += '<div class="hr"></div>';
			ret += '<div style="margin-top:-5px;font-size:11px;color:red">'+ note +'</div>';
			ret += '<div id="content-dialog-scroll" style="position: relative; margin: 0px auto; padding: 0px; width: 103%; height: 300px;overflow: hidden;" class="ps-container">';

    		ret +='<div class="content-dialog" style="width: 95%;height: auto;">';
				
				ret += '<div class="fp-container" style="height: 265px;">';
				    ret += '<div class="input_position" style="width:100%">';
					    ret += '<div style="margin-top: 10px;">';
						ret += '<label><input type="checkbox" class="fp-allUsers" value="All Users"/> All Users</label> <br />';
						ret += '<div style="margin-left: 20px;">';

						if(type!="form-admin"){
							// for department
							ret += '<div class="container-formUser">';
								ret += '<div class="formUser" rel="getDepartmentFF" ><label class="icon icon-minus"></label> <label class="font-bold">Department</label></div>';
								ret += '<div class="getDepartmentFF" style="display:inline-block;width:100%;margin-left:10px;margin-top:5px;">';
								
								var ctr_dept = 0;
								if(departments){
									departments = JSON.parse(departments);
									$.each(departments,function(key, val){
										ret += '<div style="width:30%;float:left;"> ';
										//setCheckedArray(value, arr)
											ret += '<label class="tip" title="'+ val.department +'"><input type="checkbox" class="fp-user departments" '+ self.setCheckedArray(val.id, departments_arr) +' value="'+ val.id +'"/> <span class="limit-text-ws">'+ val.department +'</span></label>';
										ret += '</div>';
										ctr_dept++
									})
								}
								if(ctr_dept==0){
									ret += '<span style="color:red">No Department</span>';
								}
								ret += '</div>';
							ret += '</div>';
							// for position
							ret += '<div class="container-formUser">';
								ret += '<div class="formUser" rel="getPositionFF" ><label class="icon icon-minus"></label> <label class="font-bold">Position</label></div>';
								ret += '<div class="getPositionFF" style="display:inline-block;width:100%;margin-left:10px;margin-top:5px;">';
									
									var ctr_pos = 0;
									if(positions){
										positions = JSON.parse(positions);
										$.each(positions,function(key, val){
											if(val.position !=""){
												ret += '<div style="width:30%;float:left;"> ';
													ret += '<label class="tip" title="'+ val.position +'"><input type="checkbox" class="fp-user positions" '+ self.setCheckedArray(val.position, positions_arr) +' value="'+ val.position +'"/> <span class="limit-text-ws">'+ val.position +'</span></label>';
												ret += '</div>';
												ctr_pos++;
											}
										})
										
									}
								if(ctr_pos==0){
									ret += '<span style="color:red">No Positions</span>';
								}	
								ret += '</div>';
							ret += '</div>';
						}else{
							users = $(".users-admin").text();
						}
						
						//for users
						ret += '<div class="container-formUser">';
						ret += '<div class="formUser" rel="getUsersFF" ><label class="icon icon-minus"></label> <label class="font-bold">Users</label></div>';
							ret += '<div class="getUsersFF" style="display:inline-block;width:100%;margin-left:10px;margin-top:5px;">';
								
								var ctr_usr = 0
								if(users){
									users = JSON.parse(users);
									$.each(users,function(key, val){
										ret += '<div style="width:30%;float:left;"> ';
											ret += '<label class="tip" title="'+ val.first_name +' '+ val.last_name +'"><input type="checkbox" class="fp-user users" '+ self.setCheckedArray(val.id, users_arr) +' value="'+ val.id +'"/> <span class="limit-text-ws">'+ val.first_name +' '+ val.last_name +'</span></label>';
										ret += '</div>';
										ctr_usr++
									})
									
								}
								if(ctr_usr==0){
									ret += '<span style="color:red">No Users</span>';
								}	
						ret += '</div>';
						ret += '</div>';
							ret += '</div>';
						ret += '</div>';
			ret += '</div>';
		ret += '</div>';
		ret += '</div>';
		ret += '</div>';
		ret += '<div class="fields">';

		    ret += '<div class="label_basic"></div>';
		    ret += '<div class="input_position" style="margin-top:5px;text-align:right;">';
			ret += '<input type="button" class="btn-blueBtn save_form_privacy" data-type="'+ type +'" value="Save">     ';
			ret += '<input type="button" class="btn-basicBtn" id="popup_cancel" value="Cancel">';
		    ret += '</div>';
		ret += '</div>';	
		return ret;
	},
	saveFormPrivacy : function (obj){
		var data_type = $(obj).attr("data-type");
		var json = $("body").data();
		var json_privacy = {};
		var departments = new Array();
		var positions = new Array();
		var users = new Array();
		
		//for deoartments
		$(".departments").each(function(){
			if($(this).prop("checked")){
				departments.push($(this).val());
			}
		})
		//for positions
		$(".positions").each(function(){
			if($(this).prop("checked")){
				positions.push($(this).val());
			}
		})
		//for users
		$(".users").each(function(){
			if($(this).prop("checked")){
				users.push($(this).val());
			}
		})

		//
		json_privacy['departments'] = departments;
		json_privacy['positions'] = positions;
		json_privacy['users'] = users;
		//
		json[''+ data_type +''] = json_privacy;
		
		//close the window
		$("#popup_cancel").click();

	},
	"checkAllUsers" : function(obj){
		if($(obj).prop("checked")){
			$(obj).closest(".fp-container").find(".fp-user").prop("checked",true);
		}else{
			$(obj).closest(".fp-container").find(".fp-user").prop("checked",false);
		}
	},
	"setCheckedArray" : function(value, arr){
		// if(value.indexOf(arr)>=0){
	    // 	return "checked='checked'";
	    // }
	    for(var i in arr){
	    	if(value==arr[i]){
	    		return "checked='checked'";
	    		break;
	    	}
	    }
	},
	"defaultChecked": function(){
		var json = $("body").data();
		var json_privacy = {};
		var departments_arr = new Array();
		var positions_arr = new Array();
		var users_arr = new Array();

		var departments = $(".departments").text();
		if(departments){
			departments = JSON.parse(departments);
			$.each(departments,function(key, val){
				departments_arr.push(val.id);
			})
		}
		//for positions
		var positions = $(".positions").text();
		if(positions){
			positions = JSON.parse(positions);
			$.each(positions,function(key, val){
				positions_arr.push(val.position);
			})
		}
		//for users
		var users = $(".users").text();
		if(users){
			users = JSON.parse(users);
			$.each(users,function(key, val){
				users_arr.push(val.id);
			})
		}

		//
		json_privacy['departments'] = departments_arr;
		json_privacy['positions'] = positions_arr;
		json_privacy['users'] = users_arr;
		//
		json['form-authors'] = json_privacy;
		json['form-admin'] = json_privacy;
	},
	setCheckAllChecked : function(clickedEle){
		dialogContainer = $(clickedEle).closest(".fp-container");
		totalCheckBox = dialogContainer.find(".fp-user").length;
		totalCheckBoxChecked = dialogContainer.find(".fp-user:checked").length;
		if(totalCheckBox == totalCheckBoxChecked){
			dialogContainer.find(".fp-allUsers").attr("checked",true);
		}else{
			dialogContainer.find(".fp-allUsers").attr("checked",false);
		}
	},
	bindOnClickCheckBox:function(){
		self = this;
		dialogContainer = $("#popup_container");
		dialogContainer.find(".fp-user").on({
			"click":function(ee){
				self.setCheckAllChecked(this);
			}
		})
	}
}

$(document).ready(function(){
	 //$(".form_settings_open").formbuilder({auto_open:"true"});
    $(".form_settings_open").formbuilder({type:"open"}).formbuilder({type:"close"});


    //check all fields(enabled,hidden,required)
    $("body").on("click",".checkAllFields",function(){
    	CheckProperties.checkAll(this,".container-fields");
    })

    
    
    //set form authors

	$(".form-authors").click(function(){
    	RequestPivacy.authors();
    })    

    //set form readers

    // $(".form-readers").click(function(){
    // 	RequestPivacy.readers();
    // })
	$("body").on("click",".form-readers",function(){
		RequestPivacy.readers();
	})
	$("body").on("click",".form-admin",function(){
		RequestPivacy.admin();
	})
	$("body").on("click",".form-customized",function(){
		// alert(123123)
		RequestPivacy.customizedPrint();
	})
    //check all
    $("body").on("click",".fp-allUsers",function(){
    	RequestPivacy.checkAllUsers(this);
    })

    $("body").on("click",".save_form_privacy",function(){
    	RequestPivacy.saveFormPrivacy(this);
    })

})


CheckProperties = {
	checkAll : function(obj,container){
		var self = $(obj);
		if(self.prop("checked")==true){
			self.closest(container).find("[type='checkbox']").prop("checked",true);
		}else{
			self.closest(container).find("[type='checkbox']").prop("checked",false);
		}
	},
	setCheckAllChecked : function(obj,container,checkAll){
		dialogContainer = $(container);
		totalCheckBox = dialogContainer.find(obj).length;
		totalCheckBoxChecked = dialogContainer.find(obj+":checked").length;
		console.log(totalCheckBox+" "+totalCheckBoxChecked);
		if(totalCheckBox == totalCheckBoxChecked){
			dialogContainer.find(checkAll).attr("checked",true);
		}else{
			dialogContainer.find(checkAll).attr("checked",false);
		}
	},
	bindOnClickCheckBox:function(obj,dialogContainer,checkAll){
		self = this;
		$(dialogContainer).find(obj).on({
			"click":function(ee){
				var obj = "."+$(this).attr("class");
				self.setCheckAllChecked(obj,dialogContainer,checkAll);
			}
		})
	}
}